<template>
  <a-drawer
    v-model:visible="vdata.visible"
    :mask-closable="false"
    title="代理商高级配置"
    :body-style="{ paddingBottom: '80px' }"
    width="60%"
    class="drawer-width"
    @close="vdata.visible = false"
  >
    <div style="background: #fff">
      <a-tabs v-if="vdata.visible" @change="selectTabs">
        <a-tab-pane key="applymentConfig" tab="进件配置">
          <div v-if="vdata.groupKey == 'applymentConfig'" class="account-settings-info-view" style="margin-left: 40px">
            <a-form :label-col="{ span: 4 }" :wrapper-col="{ span: 12 }">
              <a-row justify="start" type="flex" style="margin-top: 10px">
                <a-col :span="12">
                  <p>当前代理商进件配置管理方式</p>
                </a-col>
                <a-col :span="12" />
                <a-col :span="12">
                  <a-radio-group v-model:value="vdata.applymentAuditMode">
                    <a-radio value="DEF">使用默认配置</a-radio>
                    <a-radio value="CUSTOM">自定义配置</a-radio>
                  </a-radio-group>
                </a-col>
                <a-col :span="12" />
              </a-row>
              <a-row v-if="vdata.applymentAuditMode == 'CUSTOM'" justify="start" type="flex" style="margin-top: 40px">
                <a-col :span="8">
                  <p>当前代理商进件是否需要运营平台预审核</p>
                </a-col>
                <a-col :span="8">
                  <p>代理商发起进件时间限制</p>
                </a-col>
                <a-col :span="8" />
                <a-col :span="8">
                  <a-radio-group v-model:value="vdata.agentApplymentPreAudit">
                    <a-radio value="0">无需预审</a-radio>
                    <a-radio value="1">需要预审</a-radio>
                  </a-radio-group>
                </a-col>
                <a-col :span="8">
                  <a-space direction="vertical" :size="12">
                    <a-time-range-picker
                      v-model:value="vdata.agentApplyTimeLimit"
                      :show-time="{ format: 'HH:mm:ss' }"
                      format="HH:mm:ss"
                      :placeholder="['开始时间', '结束时间']"
                      :disabled="vdata.agentApplyTimeLimit == ''"
                      @change="onRangeChangeAgent"
                    />
                  </a-space>
                </a-col>
                <a-col :span="8">
                  <a-checkbox :checked="vdata.agentApplyTimeLimit == '' " @change="changeAgentRange">不限制</a-checkbox>
                </a-col>
              </a-row>
              <div style="margin-left: 20%; margin-top: 60px">
                <a-button type="primary" :loading="vdata.btnLoading" style="margin-right:8px" @click="confirmByApplymentConfig('onlySelf')">
                  <check-circle-outlined v-if="!vdata.btnLoading" />
                  确认更新
                </a-button>
                <a-button type="primary" :loading="vdata.btnLoading" @click="confirmByApplymentConfig('allCurrentAndSubAgent')">
                  <check-circle-outlined v-if="!vdata.btnLoading" />
                  确认更新并同步至所有下级代理商
                </a-button>
              </div>
            </a-form>
          </div>
        </a-tab-pane>

        <a-tab-pane key="cashoutConfig" tab="提现规则配置">
          <div v-if="vdata.groupKey == 'cashoutConfig'" class="account-settings-info-view" style="margin-left: 40px">
            <a-form ref="cashOutFormModel" :model="vdata.saveObject" :rules="vdata.rules">
              <a-row justify="space-between" type="flex">
                <a-form-item label="" name="cashoutFeeRuleType">
                  配置类型： <a-radio-group v-model:value="vdata.saveObject['cashoutFeeRuleType']">
                    <a-radio :value="1">使用系统默认</a-radio>
                    <a-radio :value="2">自定义</a-radio>
                  </a-radio-group>

                  <template v-if="vdata.saveObject['cashoutFeeRuleType'] == 2">
                    <br><br>
                    额度： 设置最低 <a-input-number v-model:value="vdata.castOutFeeRule.applyLimit" :min="0" /> 元可发起提现 <br><br>
                    规则： 提现 <a-input-number v-model:value="vdata.castOutFeeRule.freeLimit" :min="0" /> 元以内免收手续费 <br><br>
                    手续费计算模式：<br>
                  
                    <a-radio-group v-model:value="vdata.castOutFeeRule.feeType">
                      <a-radio value="FIX" style="margin-top:10px">
                        单笔固定
                        <template v-if="vdata.castOutFeeRule.feeType == 'FIX'">
                          <a-input-number v-model:value="vdata.castOutFeeRule.fixFee" :min="0" /> 元
                        </template>
                      </a-radio>
                      <br>
                      <a-radio value="SINGLE" style="margin-top:20px">
                        单笔费率
                        <template v-if="vdata.castOutFeeRule.feeType == 'SINGLE'">
                          <a-input-number v-model:value="vdata.castOutFeeRule.feeRate" :min="0" /> %
                        </template>
                      </a-radio>
                      <br>
                      <a-radio value="FIXANDRATE" style="margin-top:20px">
                        固定+费率
                        <template v-if="vdata.castOutFeeRule.feeType == 'FIXANDRATE'">
                          <a-input-number v-model:value="vdata.castOutFeeRule.fixFee" :min="0" /> 元 +  <a-input-number v-model:value="vdata.castOutFeeRule.feeRate" :min="0" /> %
                        </template>
                      </a-radio>
                    </a-radio-group>
                  </template>
                </a-form-item>
              </a-row>
              
              <a-divider orientation="left" style="color: #1A66FF;">钱包冻结金额配置项</a-divider>
              <a-row justify="space-between" type="flex">
                <a-col :span="24">
                  <a-form-item label="钱包冻结金额" name="freezeAmount">
                    <a-input-number
                      v-model:value="vdata.saveObject['freezeAmount']"
                      :min="0"
                      :precision="2"
                      addon-after="元" 
                      @change="(amount) => { return amount == 0 ? vdata.saveObject['freezeDesc'] = '' : vdata.saveObject['freezeDesc'] = vdata.saveObject['freezeDesc']}"
                    />
                  </a-form-item>
                </a-col>
                <a-col v-if="vdata.saveObject['freezeAmount'] > 0" :span="12">
                  <a-form-item label="冻结原因" name="freezeDesc">
                    <a-textarea v-model:value="vdata.saveObject['freezeDesc']" placeholder="请填写冻结原因" :rows="3" />
                  </a-form-item>
                </a-col>
              </a-row>
            </a-form>
            <div style="margin-left: 20%; margin-top: 60px">
              <a-button type="primary" :loading="vdata.btnLoading" style="margin-right:8px" @click="confirmByCashOutConfig()">
                <check-circle-outlined v-if="!vdata.btnLoading" />
                确认更新
              </a-button>
            </div>
          </div>
        </a-tab-pane>
        <a-tab-pane key="mchAuthorityConfig" tab="商户管理权限配置">
          <MchAuthorityConfig v-if="vdata.groupKey == 'mchAuthorityConfig'" :currentAgentNo="vdata.recordId" />
        </a-tab-pane>
      </a-tabs>
    </div>
  </a-drawer>
</template>
<script setup lang="ts">
import { API_URL_AGENT_CONFIG, req, API_URL_AGENT_LIST } from '@/api/manage'
import { ref, reactive, getCurrentInstance } from 'vue'
import dayjs, {Dayjs} from 'dayjs'
import MchAuthorityConfig from './MchAuthorityConfig.vue'

  const { $infoBox, $access } = getCurrentInstance()!.appContext.config.globalProperties

  const payTestBarCode = ref()
  const cashOutFormModel = ref()

  const vdata : any = reactive ({
    recordId: null, // 更新对象ID
    visible: false, // 是否显示弹层/抽屉
    btnLoading: false,
    groupKey: 'applymentConfig',
    agentApplyConfigData: [] as any, // 代理商进件配置保存对象
    applymentAuditMode: 'DEF', // DEF-平台全局默认配置 ,  CUSTOM-自定义
    agentApplymentPreAuditConfig: '0', // 当前代理商进件是否需要运营平台预审核 1-需要 0不需要
    agentApplyTimeLimit: '', // 代理商进件时间限制(回显)
    agentApplyTimeLimitSave: '', // 代理商进件时间限制（保存到后端）
    castOutFeeRule: { feeType: 'FIX', fixFee: 0, feeRate: 0, freeLimit: 0, applyLimit: 0 },// 手续费配置信息
    saveObject: {}, // 数据对象
    rules: {
      freezeAmount: [{ required: true, message: '请填写钱包冻结金额', trigger: 'blur' }],
      freezeDesc: [{ required: true, message: '请填写冻结原因', trigger: 'blur' }]
    }
  })

  // 点击不限制进件日期时显示的默认日期范围
  const initDateRange = ref<[Dayjs, Dayjs]>([
      dayjs('00:00:00', 'HH:mm:ss'),
      dayjs('23:59:59', 'HH:mm:ss'),
  ])

  // 勾选“不限制”按钮时的时间数据处理
  function changeAgentRange(value){
    if (value.target.checked) {
      vdata.agentApplyTimeLimit = ''
      vdata.agentApplyTimeLimitSave = ''
    } else {
      vdata.agentApplyTimeLimit = initDateRange.value
      vdata.agentApplyTimeLimitSave = JSON.stringify(['00:00:00', '23:59:59'])
    }
  }

  function show (recordId) { // 弹层打开事件
      vdata.recordId = recordId
      vdata.agentApplyTimeLimit = ''
      selectTabs('applymentConfig') //初始化数据
      vdata.visible = true
  }


function selectTabs (key) { // 清空必填提示
  if (key) {
    vdata.groupKey = key
    if(key == 'applymentConfig'){
      req.list(API_URL_AGENT_CONFIG, {groupKey: vdata.groupKey, agentNo: vdata.recordId}).then(res => {
        if (res != null && res.length > 0) {
          // 当前代理商进件配置管理方式 DEF-平台全局默认配置 ,  CUSTOM-自定义
          const applymentAuditModeIndex = res.findIndex((v) => v.configKey == 'applymentAuditMode')
          vdata.applymentAuditMode = (applymentAuditModeIndex > -1) ? res[applymentAuditModeIndex].configVal : 'DEF'
          // 代理商进件是否需要运营平台预审核
          const agentApplymentPreAuditIndex = res.findIndex((v) => v.configKey == 'agentApplymentPreAuditConfig')
          vdata.agentApplymentPreAudit = (agentApplymentPreAuditIndex > -1) ? res[agentApplymentPreAuditIndex].configVal : '0'
          // 代理商发起进件默认时间限制
          const agentApplyTimeLimitIndex = res.findIndex((v) => v.configKey == 'agentApplyTimeLimitConfig')
          if (agentApplyTimeLimitIndex > -1 && res[agentApplyTimeLimitIndex].configVal) {
              vdata.agentApplyTimeLimitSave = res[agentApplyTimeLimitIndex].configVal
              vdata.agentApplyTimeLimit = JSON.parse(res[agentApplyTimeLimitIndex].configVal)
              if (vdata.agentApplyTimeLimit[0]) {
                vdata.agentApplyTimeLimit[0] = dayjs(vdata.agentApplyTimeLimit[0], 'HH:mm:ss')
              }
              if (vdata.agentApplyTimeLimit[1]) {
                vdata.agentApplyTimeLimit[1] = dayjs(vdata.agentApplyTimeLimit[1], 'HH:mm:ss')
              }
          } else {
            vdata.agentApplyTimeLimit = ''
            vdata.agentApplyTimeLimitSave = ''
          }
        } else {
          vdata.applymentAuditMode = 'DEF'
          vdata.agentApplymentPreAudit = '0'
          vdata.agentApplyTimeLimit = ''
          vdata.agentApplyTimeLimitSave = ''
        }
      })
    } else if (key == 'cashoutConfig') {

      if (cashOutFormModel.value != undefined) {
        cashOutFormModel.value.resetFields()
      }

      vdata.saveObject = { 'state': 1, passwordType: 'default', isNotify: 0, addAgentFlag:  1, addMchFlag:  1, cashoutFeeRuleType: 1} // 数据清空
      req.getById(API_URL_AGENT_LIST, vdata.recordId).then(res => {
      vdata.saveObject = res
      // 钱包信息
      vdata.saveObject.freezeAmount = Number.parseFloat((res.freezeAmount / 100).toFixed(2)) || 0
      // 手续费类型
      vdata.castOutFeeRule = { feeType: 'FIX', fixFee: 0, feeRate: 0, freeLimit: 0, applyLimit: 0 }

      // 转换 提现手续费对象
      let castOutFeeRuleJSON = JSON.parse(vdata.saveObject.cashoutFeeRule)
      
        if(castOutFeeRuleJSON){

            vdata.castOutFeeRule.feeType = castOutFeeRuleJSON.feeType || 'FIX'

            if(castOutFeeRuleJSON.fixFee){
              vdata.castOutFeeRule.fixFee = Number.parseFloat((castOutFeeRuleJSON.fixFee / 100).toFixed(2))
            }
            if(castOutFeeRuleJSON.feeRate){
              vdata.castOutFeeRule.feeRate = Number.parseFloat((castOutFeeRuleJSON.feeRate * 100).toFixed(2))
            }
            if(castOutFeeRuleJSON.freeLimit){
              vdata.castOutFeeRule.freeLimit = Number.parseFloat((castOutFeeRuleJSON.freeLimit / 100).toFixed(2))
            }
            if(castOutFeeRuleJSON.applyLimit){
              vdata.castOutFeeRule.applyLimit = Number.parseFloat((castOutFeeRuleJSON.applyLimit / 100).toFixed(2))
            }
        }
      })
    }
  }
}


// 确认更新进件配置
function confirmByApplymentConfig(value) {
    let primaryStr = ''
    if (value) {
      if (value == 'onlySelf') {
        primaryStr = '注：仅当前代理商生效'
      } else if(value == 'allCurrentAndSubAgent') {
        primaryStr = '注：当前代理商及当前代理商的所有下级代理商均生效'
      }
    }

    $infoBox.confirmPrimary('确认更新进件配置吗？', primaryStr, () => {
      vdata.agentApplyConfigData = []
      vdata.btnLoading = true // 打开按钮上的 loading
      if (!vdata.applymentAuditMode) {
        vdata.applymentAuditMode = 'DEF'
      }
      vdata.agentApplyConfigData.push({ groupKey: vdata.groupKey, configKey: 'applymentAuditMode', configVal : vdata.applymentAuditMode })
      if (vdata.applymentAuditMode == 'CUSTOM') {
        vdata.agentApplyConfigData.push({ groupKey: vdata.groupKey, configKey: 'agentApplymentPreAuditConfig', configVal : vdata.agentApplymentPreAudit ? vdata.agentApplymentPreAudit : '0' })
        vdata.agentApplyConfigData.push({ groupKey: vdata.groupKey, configKey: 'agentApplyTimeLimitConfig', configVal : vdata.agentApplyTimeLimitSave })
      }
      req.updateById(API_URL_AGENT_CONFIG, vdata.groupKey, {agentNo: vdata.recordId, configData: JSON.stringify(vdata.agentApplyConfigData), updateType: value}).then(res => {
        $infoBox.message.success('更新成功')
        vdata.btnLoading = false
      }).catch(res => {
        vdata.btnLoading = false
      })
    })
}

// 进件时间限制  传给后端的格式 '' 或 时间数组字符串
function onRangeChangeAgent(value: any, dateString: any) {
  if (!dateString[0] && !dateString[1]) {
    vdata.agentApplyTimeLimitSave = ''
    return
  }
  if (dateString[0] && !dateString[1]) {
    dateString[1] = '23:59:59'
  } else if (!dateString[0] && dateString[1]) {
    dateString[0] = '00:00:00' 
  }
  vdata.agentApplyTimeLimitSave = JSON.stringify(dateString)
}

function confirmByCashOutConfig() {
  cashOutFormModel.value.validate().then(valid =>{
 // 手续费
 vdata.saveObject['cashoutFeeRule'] = null
      if(vdata.saveObject['cashoutFeeRuleType'] == 2){
        // 转换 提现手续费对象
        const castOutFeeRule : any = {}
        
        if(vdata.castOutFeeRule.freeLimit == null || vdata.castOutFeeRule.freeLimit < 0){
          return $infoBox.message.error('免收手续费不可小于0')
        }
        castOutFeeRule.freeLimit = Number.parseInt((vdata.castOutFeeRule.freeLimit * 100).toFixed(0))

        if(vdata.castOutFeeRule.applyLimit == null || vdata.castOutFeeRule.applyLimit < 0){
          return $infoBox.message.error('提现额度不可小于0')
        }
        castOutFeeRule.applyLimit = Number.parseInt((vdata.castOutFeeRule.applyLimit * 100).toFixed(0))

        castOutFeeRule.feeType = vdata.castOutFeeRule.feeType
        if(vdata.castOutFeeRule.feeType == 'FIX'){

          if(vdata.castOutFeeRule.fixFee == null || vdata.castOutFeeRule.fixFee < 0){
            return $infoBox.message.error('固定金额不可小于0')
          }
          castOutFeeRule.fixFee = Number.parseInt((vdata.castOutFeeRule.fixFee * 100).toFixed(0))

        }else if(vdata.castOutFeeRule.feeType == 'SINGLE'){

          if(vdata.castOutFeeRule.feeRate == null || vdata.castOutFeeRule.feeRate < 0){
            return $infoBox.message.error('费率不可小于0')
          }
          castOutFeeRule.feeRate = Number.parseFloat((vdata.castOutFeeRule.feeRate / 100).toFixed(4))

        }else if(vdata.castOutFeeRule.feeType == 'FIXANDRATE'){

          if(vdata.castOutFeeRule.fixFee == null || vdata.castOutFeeRule.fixFee < 0){
            return $infoBox.message.error('固定金额不可小于0')
          }
          if(vdata.castOutFeeRule.feeRate == null || vdata.castOutFeeRule.feeRate < 0){
            return $infoBox.message.error('费率不可小于0')
          }
          castOutFeeRule.fixFee = Number.parseInt((vdata.castOutFeeRule.fixFee * 100).toFixed(0))
          castOutFeeRule.feeRate = Number.parseFloat((vdata.castOutFeeRule.feeRate / 100).toFixed(4))
        }

        vdata.saveObject['cashoutFeeRule'] = JSON.stringify(castOutFeeRule)
      }  

      vdata.btnLoading = true

      req.updateById(API_URL_AGENT_LIST, vdata.recordId, vdata.saveObject).then(res => {
        $infoBox.message.success('更新成功')
        vdata.btnLoading = false
      }).catch(res => {
        vdata.btnLoading = false
      })
  })
}


defineExpose({
  show
})
</script>
<style lang="less" scoped>
  .bottom-btn{
    /deep/ div{
      display: flex;
      justify-content: center;
    }
  }
  .typePopover {
  position: absolute;
  top: -30px;
  left: 93px;
}
</style>
